package jp.sinya.register.dao;

import jp.sinya.register.bean.User;
import jp.sinya.register.constants.Constants;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.OutputFormat;
import org.dom4j.io.SAXReader;
import org.dom4j.io.XMLWriter;

import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;

@Deprecated
public class UserDao {
    private String path = Constants.PROJECT_RES_PATH + "users.xml";

    /**
     * @param username
     * @return
     */
    public User findByUserName(String username) {
        SAXReader reader = new SAXReader();
        try {
            Document document = reader.read(path);
            //通过xpath查询得到element
            Element node = (Element) document.selectSingleNode("//user[@username='" + username + "']");

            if (node == null) {
                return null;
            }

            User user = new User();
            String tempUserName = node.attributeValue("username");
            String tempPassword = node.attributeValue("password");
            user.setUsername(tempUserName);
            user.setPassword(tempPassword);

            return user;
        } catch (DocumentException e) {
            e.printStackTrace();
            throw new RuntimeException(e);
        }
    }

    public void addUser(User user) {
        SAXReader reader = new SAXReader();
        try {
            Document document = reader.read(path);
            Element root = document.getRootElement();
            //通过xpath查询得到element
            Element userElement = root.addElement("user");
            userElement.addAttribute("username", user.getUsername());
            userElement.addAttribute("password", user.getPassword());

            OutputFormat outputFormat = new OutputFormat("\t", true);
            outputFormat.setTrimText(true);//清空原来的换行和缩进，保证重新写入的时候重新统一一次格式

            //创建xml写出
            OutputStreamWriter outputStreamWriter = new OutputStreamWriter(new FileOutputStream(path), "utf-8");
            XMLWriter xmlWriter = new XMLWriter(outputStreamWriter, outputFormat);
            xmlWriter.write(document);
            xmlWriter.close();
        } catch (DocumentException e) {
            e.printStackTrace();
            throw new RuntimeException(e);
        } catch (IOException e) {

        }
    }
}
